<?php

namespace work\controllers;
use common\core\Controller;
use common\helps\Curl;
use common\helps\Log;
use common\helps\WXBizMsgCrypt;
use Yii;

class TicketYtController extends Controller
{
    public $corp_id = null;
    public $suite_id = null;
    public $enableCsrfValidation = false;
    public $token;
    public $encodingAesKey;
    public $redis;
    public $curl;
    public function init()
    {
        //此处为企业微信
        header("Content-Type:text/html; charset=utf-8");
        $this->corp_id = env('CorpID'); //服务商cropid
        $this->token = env('TOKEN_YT'); //应用token
        $this->encodingAesKey = env('EncodingAESKey_YT'); //应用 EncodingAESKey
        $this->suite_id = env('SUITE_ID_YT'); //应用ID
        $this->redis = Yii::$app->redis;
        $this->curl = new Curl();
    }

    /*
     *
     * 1.回应企业微信后台的数据回调url
     *2.回应企业微信后台的指令回调url
     *3.缓存redis，suite_ticket，suite_access_token , pre_auth_code
     *
     * */

    public function actionIndex(){
        /*
        ------------使用示例一：验证回调URL---------------
        *企业开启回调模式时，企业号会向验证url发送一个get请求

        接收到该请求时，企业应
        1.解析出Get请求的参数，包括消息体签名(msg_signature)，时间戳(timestamp)，随机数字串(nonce)以及公众平台推送过来的随机加密字符串(echostr),
        这一步注意作URL解码。
        2.验证消息体签名的正确性
        3. 解密出echostr原文，将原文当作Get请求的response，返回给公众平台
        第2，3步可以用公众平台提供的库函数VerifyURL来实现。

        */

        //以下是接收传过get传过来的参数，不同框架用不同方式获取
		$sVerifyMsgSig = urldecode(Yii::$app->request->get('msg_signature'));
		
		$sVerifyTimeStamp = urldecode(Yii::$app->request->get('timestamp'));
		
		$sVerifyNonce = urldecode(Yii::$app->request->get('nonce'));

        $echoStr = (Yii::$app->request->get('echostr'));

        //1.解密出echostr原文，将原文当作Get请求的response，返回给公众平台
        header('content-type:text'); //注意，此处不能省略
        $sEchoStr       = ""; //明文
        $wxcpt = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->corp_id); //次函数为企业微信demo中的函数，直接拿过来用
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $echoStr, $sEchoStr);
        if ($errCode == 0) { //验证成功，返回明文
            echo $sEchoStr;
            exit;
        }

        //2.接收企业微信后台推送的 suite_ticket,已post形式，每10分钟推送一次
        if(Yii::$app->request->isPost){
            //必须通过输入流方式获取post数据,，接收到的$sReqData 为xml格式，需转换成对象或其他格式
            $sReqData = file_get_contents("php://input");
            $xml =  simplexml_load_string($sReqData,'SimpleXMLElement', LIBXML_NOCDATA); // yii xml格式转成对象
            $ToUserName = $xml->ToUserName; //获取到的suite_id
            //$Encrypt = $xml->Encrypt;
            if($this->suite_id == $ToUserName){ //证明是企业微信后台推送
                $wxcpt = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $ToUserName);
                $sMsg     = '';  // 解析之后的明文
                $err_code = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sReqData, $sMsg);//var_dump($get,$err_code,$sMsg);//exit;\
                $xml = simplexml_load_string($sMsg,'SimpleXMLElement', LIBXML_NOCDATA); // yii xml格式转成对象
                if($err_code == 0){
                    switch ($xml->InfoType) {
                        case 'suite_ticket'://推送suite_ticket协议每十分钟微信推送一次
                            $suite_ticket = $xml->SuiteTicket;
                            if (!empty($suite_ticket)) {
                                //1.缓存redis suite_ticket ,过期时间 30分钟，每10分钟刷新一次，600s
                                $this->redis->set('yt_suite_ticket',$suite_ticket);
                                $this->actionGetSuiteAccessToken($suite_ticket); //获取suite_access_token
                                $this->actionGetPreAuthCode(); //获取pre_auth_code

                                echo 'success';  // 返回企业微信消息 success

                            }
                            else {
                                //错误信息
                                echo 200;
                            }

                            break;

                        case 'cancel_auth'://取消授权的通知 -- 特指套件取消授权
                            $auth_corp_id = $xml->getElementsByTagName('AuthCorpId')->item(0)->nodeValue;//普通企业的corpid
                            //自己的业务需求
                            break;

                    }
                }

            }

        }

       
    }

    //2.获取第三方应用凭证，suite_access_token 有效期7200s，存入redis
    public function actionGetSuiteAccessToken(){
        $suite_access_token = $this->redis->get(':yt_suite_access_token');
        if(!$suite_access_token){
            $url_suite_access_token = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token';
            $data_suite_access_token = [
                'suite_id' => env('SUITE_ID_YT'),
                'suite_secret' => env('SUITE_SECRET_YT'),
                'suite_ticket' => $this->redis->get('yt_suite_ticket'),
            ];
            $result_suite_access_token = $this->curl->request($url_suite_access_token,$data_suite_access_token,'post',true);
            $result_suite_access_token = json_decode($result_suite_access_token);

            $this->redis->set(':yt_suite_access_token',$result_suite_access_token->suite_access_token);//缓存suite_access_token
            $this->redis->expire(':yt_suite_access_token',7000);
        }

    }

    //3.获取预授权码  get请求 有效期1200秒  pre_auth_code
    public function actionGetPreAuthCode(){
        if(!$this->redis->get(':yt_pre_auth_code')){
            $url_pre_auth_code = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token='.$this->redis->get(':yt_suite_access_token');
            $result_pre_auth_code = $this->curl->request($url_pre_auth_code,[],'get');
            $result_pre_auth_code = json_decode($result_pre_auth_code);//获取到预授权码 $result_pre_auth_code->pre_auth_code;

            $this->redis->set(':yt_pre_auth_code',$result_pre_auth_code->pre_auth_code);
            $this->redis->expire(':yt_pre_auth_code',1000);
        }
    }



}